import { Block, Button, Text, View } from '@tarojs/components';
import {
  downloadFile,
  hideLoading,
  navigateTo,
  openDocument,
  showLoading,
  showModal,
  showToast,
  useEffect,
  useRouter,
  useShareAppMessage,
  useState
} from '@tarojs/taro';
import dayjs from 'dayjs';
import Layout from '../../components/Layout';
import XFilter from '../../components/XFilter';
import XList from '../../components/XList';
import XRow from '../../components/XRow';
import { CacheTemp } from '../../constant/cache';
import { taskPriObject, taskStatus } from '../../constant/label';
import baseService from '../../utils/baseService';
import { formatFile, formatHtml, setCache } from '../../utils/utils';
import Historys from './components/Historys';

const Detail = () => {
  const [curr, setCurr] = useState({ task: {}, actions: [], users: {} });
  const [files, setFiles] = useState([]);
  const {
    params: { id }
  } = useRouter();

  useEffect(() => {
    getRow();
  }, []);

  useShareAppMessage((res) => {
    return {
      title: curr['title'],
      path: '/pages/rd/detail?id=' + curr['task']['id']
    };
  });

  const getRow = () => {
    showLoading({ title: '操作中' });
    baseService.query('/task-view-' + id + '-.json', {}).then(({ data = {} }) => {
      console.log(data);
      hideLoading();
      if (Object.keys(data).length) {
        const bg = data.task;
        const pics = [];
        const files = [];
        if (data.task.files && Object.keys(bg.files).length) {
          Object.keys(bg.files).forEach((x) => {
            if (['png', 'jpg', 'jpeg', 'bmp', 'gif', 'webp'].includes(bg.files[x].extension)) {
              pics.push(formatHtml(`<img src="/file-read-${x}.html" />`));
            } else {
              files.push({
                title: bg.files[x].title,
                ext: bg.files[x].extension,
                url: formatFile(`/file-read-${x}.html`)
              });
            }
          });
        }
        data.task.desc = formatHtml(bg.desc || '暂无任务描述');
        data.task.storySpec = formatHtml(bg.storySpec || '暂无需求描述');
        data.task.attachment = pics.join('<br />');
        setFiles(files);
        setCurr(data);
      } else {
        showToast({ title: '不存在的task，或者无权限访问', icon: 'none' });
      }
    });
  };

  const onRedirect = (url) => {
    setCache(CacheTemp, curr);
    navigateTo({ url });
  };

  const onClose = () => {
    showModal({
      title: '操作提示',
      content: '确定要关闭吗'
    }).then(({ confirm }) => {
      if (confirm) {
        baseService
          .post(
            `/task-close-${curr['task']['id']}.json`,
            {
              status: 'closed',
              comment: '来自oa系统的关闭操作'
            },
            { isForm: true }
          )
          .then((res) => {
            console.log(res);
            getRow();
            showToast({ title: '关闭成功' });
          });
      }
    });
  };

  const onActive = () => {
    showModal({
      title: '操作提示',
      content: '确定要激活吗'
    }).then(({ confirm }) => {
      if (confirm) {
        baseService
          .post(
            `/task-activate-${curr['task']['id']}.json`,
            {
              status: 'doing',
              comment: '来自oa系统的激活操作'
            },
            { isForm: true }
          )
          .then((res) => {
            console.log(res);
            getRow();
            showToast({ title: '激活成功' });
          });
      }
    });
  };

  const onStart = () => {
    showModal({
      title: '操作提示',
      content: '确定要开始吗'
    }).then(({ confirm }) => {
      if (confirm) {
        baseService
          .post(
            `/task-start-${curr['task']['id']}.json`,
            {
              realStarted: dayjs().format('YYYY-MM-DD'),
              status: 'doing',
              comment: '来自oa系统的开始操作'
            },
            { isForm: true }
          )
          .then((res) => {
            console.log(res);
            getRow();
            showToast({ title: '操作成功' });
          });
      }
    });
  };

  const onDone = () => {
    showModal({
      title: '操作提示',
      content: '确定要完成吗'
    }).then(({ confirm }) => {
      if (confirm) {
        baseService
          .post(
            `/task-finish-${curr['task']['id']}.json`,
            {
              finishedDate: dayjs().format('YYYY-MM-DD'),
              assignedTo: curr['task']['openedBy'],
              currentConsumed: 4,
              status: 'done',
              comment: '来自oa系统的完成操作'
            },
            { isForm: true }
          )
          .then((res) => {
            console.log(res);
            getRow();
            showToast({ title: '操作成功' });
          });
      }
    });
  };

  const onCancel = () => {
    showModal({
      title: '操作提示',
      content: '确定要取消吗'
    }).then(({ confirm }) => {
      if (confirm) {
        baseService
          .post(
            `/task-cancel-${curr['task']['id']}.json`,
            {
              status: 'cancel',
              comment: '来自oa系统的取消操作'
            },
            { isForm: true }
          )
          .then((res) => {
            console.log(res);
            getRow();
            showToast({ title: '操作成功' });
          });
      }
    });
  };

  const onChangeUser = (groupIndex, value, index) => {
    const userName = Object.keys(curr['users'])[index];
    baseService
      .post(
        `/task-assignTo--${curr['task']['id']}.json`,
        {
          assignedTo: userName,
          comment: '来自oa系统的指派操作'
        },
        { isForm: true }
      )
      .then((res) => {
        console.log(res);
        getRow();
        showToast({ title: '操作成功' });
      });
  };

  const onDelete = () => {
    showModal({
      title: '操作提示',
      content: '确定要删除吗'
    }).then(({ confirm }) => {
      if (confirm) {
        baseService
          .query(
            `/task-delete-${curr['project']['id']}-${curr['task']['id']}-yes.json`,
            {}
          )
          .then((res) => {
            console.log(res);
            getRow();
            showToast({ title: '删除成功' });
          });
      }
    });
  };

  const onOpen = ({ url, ext }) => {
    showLoading({ title: '操作中' });
    downloadFile({
      url,
      success: function(res) {
        const filePath = res.tempFilePath;
        openDocument({
          filePath: filePath,
          fileType: ext,
          success: function(res) {
            hideLoading();
          },
          fail({ errMsg }) {
            showToast({ title: '打开文件失败,' + errMsg, icon: 'none' });
          }
        });
      },
      fail({ errMsg }) {
        showToast({ title: '下载文件失败,' + errMsg, icon: 'none' });
      }
    });
  };

  const onComment = () => {
    setCache(CacheTemp, curr);
    navigateTo({ url: 'comment?id=' + id });
  };

  return (
    <Layout>
      <View style={{ paddingBottom: 'calc(50px + env(safe-area-inset-bottom))' }}>
        <XList isCustomize={true}>
          <View style={{ display: 'flex', flexWrap: 'wrap' }}>
            <Text decode={true}> {curr['title']}</Text>
          </View>
          <XRow style={{ fontSize: '12px', color: '#8c8c8c' }}>
            <XRow>
              <View
                style={{
                  marginRight: '5px'
                }}
              >
                #{curr['task']['id']}
              </View>
              <View style={{ color: '#13c2c2', marginRight: '5px' }}>
                <View
                  style={{
                    color: (taskPriObject[curr['task']['pri']] || {}).color,
                    width: '15px',
                    height: '15px',
                    fontSize: '12px',
                    borderRadius: '50%',
                    border: '2px solid ' + (taskPriObject[curr['task']['pri']] || {}).color,
                    display: 'flex',
                    justifyContent: 'center',
                    alignItems: 'center'
                  }}
                >
                  {(taskPriObject[curr['task']['pri']] || {}).label}
                </View>
              </View>
              <View
                style={{
                  color: (taskStatus[curr['task']['status']] || {}).color,
                  marginRight: '5px'
                }}
              >
                {(taskStatus[curr['task']['status']] || {}).label}
              </View>
              <View>{curr['project']['name']}</View>
            </XRow>
          </XRow>
        </XList>
        <XList isCustomize={true}>
          <XRow>
            <View style={{ display: 'flex', alignItems: 'center' }}>
              <XFilter
                filterOptions={[Object.values(curr.users)]}
                defaultLabel="指派给"
                onChange={onChangeUser}
                valueStyle={{
                  height: '29px',
                  padding: '0 6px',
                  borderRadius: '2px',
                  color: '#333',
                  background: '#d5d5d5',
                  fontSize: '12px'
                }}
              ></XFilter>
            </View>
            <View style={{ display: 'flex', alignItems: 'center' }}>
              {curr['task']['deleted'] === '0' && (
                <View style={{ marginRight: '15px' }}>
                  <Button type="default" size="mini" onClick={onDelete}>
                    删除
                  </Button>
                </View>
              )}
              {curr['task']['status'] === 'done' && (
                <View style={{ marginRight: '15px' }}>
                  <Button type="warn" size="mini" onClick={onClose}>
                    关闭
                  </Button>
                </View>
              )}
              {curr['task']['deleted'] !== 1 &&
                ['closed', 'cancel', 'done'].includes(curr['task']['status']) && (
                  <View style={{ marginRight: '15px' }}>
                    <Button type="primary" size="mini" onClick={onActive}>
                      激活
                    </Button>
                  </View>
                )}
              {curr['task']['status'] === 'wait' && (
                <View style={{ marginRight: '15px' }}>
                  <Button type="primary" size="mini" onClick={onStart}>
                    开始
                  </Button>
                </View>
              )}
              {curr['task']['status'] === 'doing' && (
                <Block>
                  <View style={{ marginRight: '15px' }}>
                    <Button type="primary" size="mini" onClick={onCancel}>
                      取消
                    </Button>
                  </View>
                  <View style={{ marginRight: '15px' }}>
                    <Button type="primary" size="mini" onClick={onDone}>
                      完成
                    </Button>
                  </View>
                </Block>
              )}
            </View>
          </XRow>
        </XList>
        <XList isCustomize={true}>
          <wxparser rich-text={curr['task']['desc'] || ''} />
        </XList>
        <XList isCustomize={true}>
          <wxparser rich-text={curr['task']['storySpec'] || ''} />
          {curr['task']['attachment'] && (
            <wxparser rich-text={'<br />[附件]<br />' + curr['task']['attachment']} />
          )}
          {files.length > 0 && (
            <View>
              [文件附件]
              {files.map((x) => (
                <View key={x.url} onClick={onOpen.bind(this, x)} style={{ color: '#1890ff' }}>
                  {x.title}
                </View>
              ))}
            </View>
          )}
        </XList>
        <XList isCustomize={true}>
          <Historys users={curr.users} actions={Object.values(curr.actions)}></Historys>
        </XList>
      </View>

      <View
        style={{
          position: 'fixed',
          bottom: 0,
          marginBottom: 0,
          width: '100%',
          background: '#23d1a5',
          color: '#fff',
          zIndex: 10000,
          display: 'flex',
          justifyContent: 'center',
          alignItems: 'center',
          paddingTop: '14px',
          paddingBottom: 'calc(14px + env(safe-area-inset-bottom))'
        }}
        onClick={onComment}
      >
        添加Task备注
      </View>
    </Layout>
  );
};
Detail.config = {
  navigationBarTitleText: 'Task详情',
  usingComponents: {
    wxparser: 'plugin://wxparserPlugin/wxparser'
  }
};
export default Detail;
